<?php

namespace app\home\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use app\common\controller\Email;
use app\common\controller\Get;
use app\common\controller\Common;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

/**
 * 作业人员列表管理
 * Class User
 * @package app\worker\controller
 */
class User extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'User';

    /**
     * 作业人员列表管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '作业人员列表管理';
        $query = $this->_query($this->table)
            ->alias('u')
            ->join('body b', 'b.id=u.body_id', 'left')
            ->dateBetween('u.create_at')
            ->where(['u.is_deleted' => '0'])
            ->like('u.name#name,b.body_name#body_name,u.phone#phone')
            ->equal('u.status#status')
            ->field('u.*,b.body_name')
            ->order('u.create_at desc, id desc');
        if (request()->get('export')) {
            $query->page(false);
        } else {
            $query->page();
        }
    }

    protected function _index_page_filter(&$data)
    {
        //导出数据
        if (request()->get('export')) {
            foreach ($data as &$v) {
                $v['type'] = Get::type()[$v['type']];
                $v['classify'] = Get::classify()[$v['classify']];
                $v['att'] = Get::att()[$v['att']];
                $v['payment_way'] = Get::payment_way()[$v['payment_way']];
                $v['pay_way'] = Get::pay_way()[$v['pay_way']];
            }
            $name = date('Y-m-d') . '人员列表信息';
            $head = ['ID', '姓名', '类型', '分类', '属性', '主体名称', '结算方式', '支付方式', '手机', '入职时间', '离职时间', '银行卡号', '身份证', '车牌号', '车型', '添加时间'];
            //数据中对应的字段，用于读取相应数据：
            $keys = ['id', 'name', 'type', 'classify', 'att', 'body_name', 'payment_way', 'pay_way', 'phone', 'in_time', 'out_time', 'bank_number', 'ID_number', 'car_number', 'car_type', 'create_at'];
            Common::export($name, $data, $head, $keys);
        }
    }

    /**
     * 添加作业人员
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->_form($this->table, 'form');
    }


    /**
     * 修改作业人员
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->_form($this->table, 'form');
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if (request()->isPost()) {
            //0周结=1临时 1月结=0固定
            $data['classify'] = $data['payment_way'] ? 0 : 1;
            if ($data['att'] != 0 && $data['att'] != 2) {
                $data['body_id'] = 0;
            }
            //同姓名 主体 类型 分类 属性 手机的人员唯一
            $where = [
                ['is_deleted', '=', 0],
                ['name', '=', $data['name']],
                ['body_id', '=', $data['body_id']],
                ['type', '=', $data['type']],
                ['classify', '=', $data['classify']],
                ['att', '=', $data['att']],
                ['phone', '=', $data['phone']]
            ];
            if ($data['id']) {
                $where[] = ['id', '<>', $data['id']];
            }
            $res = Db::name($this->table)->where($where)->find();
            if ($res) {
                $this->error('该人员信息已存在，不可重复添加');
            }
        }
    }

    /**
     * 更改作业人员状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
        $this->_save($this->table, ['status' => input('status', '0')]);
    }

    /**
     * 删除作业人员
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 按att获取主体信息
     */
    public function getBodys()
    {
        $where = [
            'is_deleted' => 0,
            'status' => 1,
            'att' => request()->get('att')
        ];
        $bodys = Db::name('Body')
            ->where($where)
            ->order('create_at desc')
            ->select();
        $this->success('获取成功', $bodys);
    }

    /**
     * 批量导出
     * @auth true
     */
    public function export()
    {
    }

    /**
     * 批量导入
     * @auth true
     */
    public function import()
    {
        set_time_limit(60); //限制页面执行时间60s
        $file = $_FILES['file']['tmp_name']; //临时文件路径或者文件url
        
        try {
            $file = iconv("utf-8", "gb2312", $file); //转码
            if (empty($file) or !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }
            $objReader = IOFactory::createReader('Xlsx');
            if (!$objReader->canRead($file)) {
                $objReader = IOFactory::createReader('Xls');
                if (!$objReader->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }
            $objReader->setReadDataOnly(true); //忽略任何格式的信息
            $objPHPExcel = $objReader->load($file);
            $worksheet = $objPHPExcel->getActiveSheet();
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $types = Get::type();
            $atts = Get::att();
            $payment_ways = Get::payment_way();
            $pay_ways = Get::pay_way();
            $keys = [
                'name', 'type', 'att', 'body_name', 'payment_way', 'pay_way', 'phone', 'in_time', 'out_time',
                'bank_number', 'ID_number', 'car_number', 'car_type'
            ];
            $data = [];
            $msg = '';
            
            for ($j = 2; $j <= $highestRow; $j++) {
                foreach ($keys as $k => $v) {
                    $$v = $worksheet->getCellByColumnAndRow($k + 1, $j)->getValue();
                }
                $type = array_search($type, $types);
                $att = array_search($att, $atts);
                $payment_way = array_search($payment_way, $payment_ways);
                $pay_way = array_search($pay_way, $pay_ways);
                $in_time = $in_time ? date('Y-m-d', Date::excelToTimestamp($in_time)) : ""; //转化为时间类型
                $out_time = $out_time ? date('Y-m-d', Date::excelToTimestamp($out_time)) : ""; //转化为时间类型
                //0周结=1临时 1月结=0固定
                $classify = $payment_way ? 0 : 1;
                
                if (empty($name)) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,姓名没有填写,插入失败</p>';
                } elseif ($type === '' || $type === null) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,类型填写错误,插入失败</p>';
                } elseif ($att === '' || $att === null) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,属性填写错误,插入失败</p>';
                } elseif ($payment_way === '' || $payment_way === null) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,结算方式填写错误,插入失败</p>';
                } elseif ($pay_way === '' || $pay_way === null) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,支付方式填写错误,插入失败</p>';
                }  elseif (empty($phone)) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,手机号没有填写,插入失败</p>';
                }  elseif (empty($in_time)) {
                    $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,入职时间没有填写,插入失败</p>';
                } else {
                    //获取主体id
                    if ($att != 0 && $att != 2) {
                        $body_id = 0;
                    } else {
                        $body_id = Db::name('body')
                            ->where('is_deleted', 0)
                            ->where('att', $att)
                            ->where('status', 1)
                            ->where('body_name', $body_name)
                            ->order('create_at desc')
                            ->value('id');
                        $body_id = $body_id ? $body_id : '';
                    }
                    $where = [
                        ['is_deleted', '=', 0],
                        ['name', '=', $name],
                        ['body_id', '=', $body_id],
                        ['type', '=', $type],
                        ['classify', '=', $classify],
                        ['att', '=', $att],
                        ['phone', '=', $phone]
                    ];
                    if ($body_id === '') {
                        $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,没有找到该主体名称,插入失败</p>';
                    } elseif (Db::name($this->table)->where($where)->find()) { //同姓名 主体 类型 分类 属性 手机的人员唯一
                        $msg .=  '<p style="color:red">第' . ($j - 1) . '条数据,该人员信息已存在,插入失败</p>';
                    } else {
                        $data[] = [
                            'name' => $name,
                            'type' => $type,
                            'classify' => $classify,
                            'att' => $att,
                            'body_id' => $body_id,
                            'payment_way' => $payment_way,
                            'pay_way' => $pay_way,
                            'phone' => $phone,
                            'bank_number' => $bank_number,
                            'ID_number' => $ID_number,
                            'car_number' => $car_number,
                            'in_time' => $in_time,
                            'out_time' => $out_time,
                        ];
                    }
                }
            }
            halt($data);
            $result = Db::name('User')->data($data)->limit(100)->insertAll(); // 分批插入数据
            $msg .= '<p style="color:blue">导入完成</p><p style="color:blue">总共' . ($highestRow - 1) . '条数据</p>
                    <p style="color:blue">成功' . count($data) . '条数据</p>
                    <p style="color:red">失败' . ($highestRow - count($data) - 1) . '条数据</p>';
            return json(['code' => 1, 'msg' => $msg]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
}
